<template>
	<view class="container">
		<!-- 地图容器 -->
		<map id="map" :latitude="center.latitude" :longitude="center.longitude" :scale="14" class="map-container"
			show-location :enable-scroll="true" :markers="markers" @markertap="handleMarkerTap">
		</map>

		<!-- 搜索框 -->
		<view class="search-container">
			<view class="search-box">
				<uni-icons type="search" size="28" color="#999999" class="search-icon" />
				<input class="search-input" type="text" placeholder="" v-model="userName" @input="handleSearchInput"
					@confirm="handleSearchConfirm" />
			</view>
		</view>

		<!-- 商家列表 - 默认隐藏，优化滚动样式 -->
		<view class="business-list" v-if="showBusinessList && selectedBusiness">
			<!-- 滚动容器 -->
			<view class="business-scroll">
				<view class="business-item" @click="makeCall(selectedBusiness)">
					<image class="business-avatar" :src="selectedBusiness.avatar" />
					<view class="business-info">
						<text class="business-name">{{ selectedBusiness?.name }}</text>
						<text class="business-desc">
							{{ selectedBusiness?.services && selectedBusiness?.services.join('、') }}
						</text>
					</view>
					<button class="contact-btn" @click="makeCall(selectedBusiness)">去联系</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		reactive,
		watch
	} from "vue";
	import {
		getLatitude,
		getLongitude
	} from "@/common/util.js";
	import {
		queryPeopleList
	} from "@/api/findPeople.js";
	import {
		ImgBaseUrl
	} from '@/utils/domain.js';

	// 坐标数据
	const center = reactive({
		latitude: getLatitude(),
		longitude: getLongitude(),
	});
	const MapInfoList = ref([]);
	const markers = ref([]);

	// 控制商家列表显示状态
	const showBusinessList = ref(false);
	// 选中的商家信息
	const selectedBusiness = ref(null);

	// 搜索框绑定数据
	const userName = ref("");
	// 防抖计时器
	const searchTimer = ref(null);

	// 跳转到找人详情页
	const makeCall = (item) => {
		uni.navigateTo({
			url: "/pages/tabBars/findPeople/peopleDetail?jobId=" + item.userId,
		});
	};

	// 获取用户位置
	const getLocation = async () => {
		try {
			const res = await new Promise((resolve, reject) => {
				uni.getLocation({
					type: "gcj02",
					success: resolve,
					fail: reject,
				});
			});
			center.latitude = res.latitude;
			center.longitude = res.longitude;
		} catch (err) {
			console.warn("获取位置失败:", err);
			uni.showToast({
				title: "请开启位置权限",
				icon: "none"
			});
		}
	};

	// 转换标记点
	const convertToMarkers = () => {
		markers.value = MapInfoList.value.map((item, index) => ({
			id: index,
			latitude: item.lat,
			longitude: item.lng,
			title: item.name || '商家',
			iconPath: `${ImgBaseUrl}near-marsk.png`,
			width: 50,
			height: 58,
			data: {
				index
			}
		}));
	};

	// 点击标记点事件
	const handleMarkerTap = (e) => {
		const markerId = e.detail.markerId;
		selectedBusiness.value = MapInfoList.value[markerId];
		showBusinessList.value = true;
	};

	// 搜索输入防抖
	const handleSearchInput = (e) => {
		if (searchTimer.value) clearTimeout(searchTimer.value);
		searchTimer.value = setTimeout(() => {
			userName.value = e.detail.value.trim();
			queryPeopleListApi();
		}, 300);
	};

	// 回车确认搜索
	const handleSearchConfirm = () => {
		if (searchTimer.value) clearTimeout(searchTimer.value);
		queryPeopleListApi();
	};

	// 调用接口
	const queryPeopleListApi = async () => {
		uni.showLoading({
			title: "搜索中..."
		});
		try {
			const params = {
				pageNum: 1,
				pageSize: 9999,
				categoryId: 1,
				lat: getLatitude(),
				lng: getLongitude(),
				userName: userName.value,
			};
			const res = await queryPeopleList(params);
			if (res.code === 200) {
				MapInfoList.value = res.rows || [];
				convertToMarkers();
				showBusinessList.value = false;
				selectedBusiness.value = null;
				if (MapInfoList.value.length === 0) {
					uni.showToast({
						title: "未找到相关商家",
						icon: "none"
					});
				}
			} else {
				uni.showToast({
					title: res.msg || "搜索失败",
					icon: "none"
				});
			}
		} catch (err) {
			console.error("接口请求失败:", err);
			uni.showToast({
				title: "网络异常，请重试",
				icon: "none"
			});
		} finally {
			uni.hideLoading();
		}
	};

	// 初始化
	onMounted(async () => {
		await getLocation();
		queryPeopleListApi();
	});

	// 监听数据更新标记点
	watch(MapInfoList, () => {
		convertToMarkers();
	});
</script>

<style lang="scss" scoped>
	// 根容器禁止全局滚动
	.container {
		position: relative;
		display: flex;
		flex-direction: column;
		width: 100%;
		height: 100vh;
		overflow: hidden;
		/* 关键：防止页面整体滚动 */

		.map-container {
			width: 100%;
			height: 100%;
			/* 改用100%避免vh在移动端的兼容性问题 */
		}

		.search-container {
			position: absolute;
			top: 100rpx;
			left: 20rpx;
			right: 20rpx;
			z-index: 10;

			.search-box {
				flex: 1;
				display: flex;
				align-items: center;
				background-color: #fff;
				border-radius: 36rpx;
				padding: 0 20rpx;
				box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);

				.search-icon {
					width: 40rpx;
					margin-right: 10rpx;
				}

				.search-input {
					flex: 1;
					height: 72rpx;
					font-size: 28rpx;
					color: #333;
					border: none;
					outline: none;
					background: transparent;

					&::placeholder {
						color: #999;
					}
				}
			}
		}

		.business-list {
			position: absolute;
			bottom: 322rpx;
			left: 20rpx;
			right: 20rpx;
			z-index: 10;
			background: #fff;
			border-radius: 16rpx;
			padding: 20rpx;
			box-shadow: 0 2rpx 15rpx rgba(0, 0, 0, 0.15);
			max-height: 300rpx;
			/* 限制最大高度，避免溢出 */

			// 滚动容器（隐藏默认滚动条）
			.business-scroll {
				width: 100%;
				height: 100%;
				overflow-y: auto;
				/* 允许垂直滚动 */

				// 隐藏滚动条（兼容多端）
				&::-webkit-scrollbar {
					display: none;
					/* Chrome/Safari/Opera */
				}

				-ms-overflow-style: none;
				/* IE/Edge */
				scrollbar-width: none;
				/* Firefox */
			}

			.business-item {
				display: flex;
				align-items: center;
				padding: 20rpx 0;

				.business-avatar {
					width: 100rpx;
					height: 100rpx;
					border-radius: 50%;
					margin-right: 20rpx;
				}

				.business-info {
					display: flex;
					flex-direction: column;
					flex: 1;

					.business-name {
						font-size: 32rpx;
						color: #333;
						font-weight: 500;
					}

					.business-desc {
						font-size: 24rpx;
						color: #999;
						font-weight: 400;
						margin-top: 8rpx;
					}
				}

				.contact-btn {
					height: 60rpx;
					background: #2F80ED;
					color: #fff;
					font-size: 24rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					border-radius: 30rpx;
					font-weight: 400;
				}
			}
		}
	}
</style>